package com.zndroid.logcat.displayer;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;

import com.zndroid.logcat.R;
import com.zndroid.logcat.assist.OnClickListener;
import com.zndroid.logcat.assist.OnToastListener;
import com.zndroid.logcat.assist.XToast;
import com.zndroid.logcat.assist.draggable.SpringDraggable;

/**
 * 控制显示日志悬浮窗体
 * */
public final class FloatingWindow extends XToast implements OnClickListener, OnToastListener {
    private final LogcatWindow logcatWindow;

    public FloatingWindow(Activity activity) {
        super(activity);
        initWindow(activity);
        logcatWindow = new LogcatWindow(activity);
    }

    public FloatingWindow(Application application) {
        super(application);
        initWindow(application);
        logcatWindow = new LogcatWindow(application);
    }

    private void initWindow(Context context) {
        ImageView imageView = new ImageView(context);
        imageView.setId(android.R.id.icon);
        imageView.setImageResource(R.drawable.log_selector_floating);
        setView(imageView);

        int size = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 45, context.getResources().getDisplayMetrics());
        setWidth(size);
        setHeight(size);

        setAnimStyle(android.R.style.Animation_Toast);
        setDraggable(new SpringDraggable());
        setGravity(Gravity.END | Gravity.CENTER_VERTICAL);

        setOnClickListener(android.R.id.icon, this);
        setOnToastListener(this);
    }

    @Override
    public void onClick(XToast toast, View view) {
        if (null != logcatWindow && logcatWindow.isShow()) return;
        if (null != logcatWindow)
            logcatWindow.show();
        else
            throw new UnsupportedOperationException("not null,ok?");
    }

    @Override
    public void onShow(XToast toast) {
        if (null != logcatWindow) {
            logcatWindow.logStart();
        }
    }

    @Override
    public void onDismiss(XToast toast) {
        if (null != logcatWindow) {
            logcatWindow.logStop();
        }
    }
}